<?php
/**
 * Created by PhpStorm.
 * User: 13095
 * Date: 2018/9/19
 * Time: 10:08
 */

namespace app\common\model;


use think\Model;

class Base extends Model
{
    /**
     * 獲取列表數據
     * @param array $data
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lists($data = array())
    {
        if(!empty($data)){
            if(!empty($data['alias']))$this->alias($data['alias']);
            if(!empty($data['field']))$this->field($data['field']);
            if(!empty($data['order']))$this->order($data['order']);
            if(!empty($data['where']))$this->where($data['where']);
            if(!empty($data['join']))$this->where($data['join']);
            if(!empty($data['page']) && !empty($data['limit']))$this->page($data['page'],$data['limit']);
            $role_data = $this->select();
            if (!empty($role_data)) $role_data = $role_data->toArray();
            return $role_data;
        }else{
            return '数据不存在';
        }
    }

    /**
     * 獲取單條數據
     * @param $data
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOneData($data)
    {
        if (!empty($data)) {
            if (!empty($data['alias'])) $this->alias($data['alias']);
            if (!empty($data['field'])) $this->field($data['field']);
            if (!empty($data['order'])) $this->order($data['order']);
            if (!empty($data['where'])) $this->where($data['where']);
            if (!empty($data['join'])) $this->join($data['join']);
            $role_data = $this->find();
            return $this->isNull($role_data);
        } else {
            return '数据不存在';
        }
    }

    /**
     * 數據添加
     * @param $data
     * @return bool|string
     */
    public function add($data)
    {
        if (empty($data)) {
            return '数据不存在';
        }
        $res = $this->allowField(true)->save($data);
        return $res ? true : '新增失败';
    }

    /**
     * 數據編輯
     * @param $data
     * @return bool|string
     */
    public function edit($data)
    {
        if (empty($data)) {
            return '数据不存在';
        }
        $res = $this->allowField(true)->save($data['data'], $data['where']);
        return $res ? true : '编辑失败';
    }

    /**
     * 過濾null值
     * @param $data
     * @return array
     */
    public function isNull($data)
    {
        $res = is_null($data) ? array() : $data->toArray();
        return $res;
    }
}